package com.obuge.yfly.controller;

import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.obuge.yfly.Interceptor.ResultData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileUploadController {
    @Value("${file-save-path}")
    private String fileSavePath;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    @PostMapping("/upload")
    public ResultData upload(MultipartFile file, HttpServletRequest req) {
        String filePath = "";
        File folder = new File(fileSavePath);
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() +
                oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            file.transferTo(new File(folder, newName));
            filePath = "/uploads/" + newName;
        } catch (IOException e) {
            e.printStackTrace();
            return ResultData.fail("上传文件失败");
        }
        return ResultData.success(filePath);
    }
}

